#include "engine.h"
#include "soundentity.h"

CSoundManager* SOUNDMAN=NULL;

DEFINE_ENTITY(soundentity_t,entity_t);
PROPERTY_BINDING_BEGIN(soundentity_t)
	BIND_PROPERTY_DATA(soundentity_t,wavfile,stringhash,&sound_property_data);
PROPERTY_BINDING_END

soundentity_t::soundentity_t()
{
	sound=NULL;
}

void soundentity_t::onload()
{
	entity_t::onload();
	if (wavfile.value!=0)
	{
		string wav=stringhelper::remove_extension(*wavfile.str)+".wav";
		SOUNDMAN->Create(&sound,(LPTSTR )wav.c_str(),0,GUID_NULL,5);
	}
}

soundentity_t::~soundentity_t()
{
	if (sound)
	{
		delete sound;
	}
};

void soundentity_t::play(bool loop/* =false */)
{
	if (!sound)
	{
		return;
	}

	sound->Play(0, loop ? DSBPLAY_LOOPING : 0);
}
void soundentity_t::stop()
{
	if (!sound)
	{
		return;
	}

	sound->Stop();
}

void soundentity_t::exit()
{
	if (sound)
		sound->Stop();
}

#ifdef LEO_DESIGNER
void soundentity_t::onchangeproperty(const stringhash& propname)
{
	entity_t::onchangeproperty(propname);

	if (propname=="wavfile")
	{
		if (sound)
			delete sound;
		if (wavfile.value!=0)
		{
			string wav=stringhelper::remove_extension(*wavfile.str)+".wav";
			SOUNDMAN->Create(&sound,(LPTSTR )wav.c_str(),0,GUID_NULL,5);
		}
		else
			sound=NULL;

	}
}


#endif

#include "entity/game.h"
#include "entity/scene.h"
void play_sfx(const string& n,bool loop)
{
	soundentity_t* se=(soundentity_t*)GAME->scene->getentity(n.c_str());

	if (se && se->isa(soundentity_t::get_class_typeid()))
	{
		se->play(loop);
	}
}

void stop_sfx(const string& n)
{
	soundentity_t* se=(soundentity_t*)GAME->scene->getentity(n.c_str());

	if (se && se->isa(soundentity_t::get_class_typeid()))
	{
		se->stop();
	}
}

#include "script/script.h"
script_fn_registering_begin(sound)
register_script_fn("void playsfx(const string& in, bool)",play_sfx);
register_script_fn("void stopsfx(const string& in)",stop_sfx);
script_fn_registering_end
